<!-- 人工导入 -->
<template>
	<div class="manual-import">
		<el-form :inline="true" ref="queryRef" class="form-inline" label-position="right" :model="params" label-width="200px">
			<el-row justify="center">
				<el-col :span="11">
					<el-form-item label="区域：" class="form-item" prop="region">
						<el-form-item prop="province" style="width: 120px; margin-right: 10px">
							<el-select v-model="params.province" placeholder="请选择省" @change="chooseProvince" value-key="id">
								<el-option v-for="item in provinceData" :key="item.id" :label="item.name" :value="item">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item prop="city" style="width: 120px; margin-right: 10px">
							<el-select v-model="params.city" placeholder="请选择市" @change="chooseCity" clearable value-key="id">
								<el-option v-for="item in cityData" :key="item.id" :label="item.name" :value="item">
								</el-option>
							</el-select>
						</el-form-item>
						<el-form-item prop="county" style="width: 120px">
							<el-select v-model="params.county" placeholder="请选择县" @change="chooseCounty" clearable value-key="id">
								<el-option v-for="item in areaData" :key="item.id" :label="item.name" :value="item">
								</el-option>
							</el-select>
						</el-form-item>
					</el-form-item>
				</el-col>
				<el-col :span="11">
					<el-form-item label="结构类型：">
						<el-col :span="12">
							<el-form-item prop="structureType">
								<el-select v-model="params.structureType" placeholder="请选择" class="form-select"
									@change="structureTypeChange" clearable>
									<el-option v-for="item in structureTypeOptions" :key="item.value" :label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="1" class="text-center">
							<span class="text-gray-500">-</span>
						</el-col>
						<el-col :span="11">
							<el-form-item prop="structureType1">
								<el-select v-model="params.structureType1" placeholder="请选择" class="form-select" clearable>
									<el-option v-for="item in structureType1Options" :key="item.value" :label="item.label"
										:value="item.value">
									</el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row justify="center">
				<el-col :span="11">
					<el-form-item label="年代：" class="form-item" prop="years">
						<el-select v-model="params.years" placeholder="请选择" class="form-select" clearable>
							<el-option v-for="item in yearsOptions" :key="item.value" :label="item.label" :value="item.value">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="11">
					<el-form-item label="设防情况：" class="form-item" prop="fortification">
						<el-select v-model="params.fortification" placeholder="请选择" class="form-select" clearable>
							<el-option v-for="item in fortificationOptions" :key="item.value" :label="item.label" :value="item.value">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row justify="center">
				<el-col :span="11">
					<el-form-item label="用途：">
						<el-col :span="12">
							<el-form-item prop="use0">
								<el-select v-model="params.use0" placeholder="请选择" class="form-select" @change="useChange" clearable>
									<el-option v-for="item in useOptions" :key="item.value" :label="item.label"
										:value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
						<el-col :span="1" class="text-center"><span class="text-gray-500">-</span></el-col>
						<el-col :span="11">
							<el-form-item prop="use1">
								<el-select v-model="params.use1" placeholder="请选择" class="form-select" clearable>
									<el-option v-for="item in useOptions1" :key="item.value" :label="item.label"
										:value="item.value"></el-option>
								</el-select>
							</el-form-item>
						</el-col>
					</el-form-item>
				</el-col>
				<el-col :span="11">
					<el-form-item label="层数：" class="form-item" prop="cs">
						<el-select v-model="params.cs" placeholder="请选择" class="form-select" clearable :disabled="disabledcs">
							<el-option v-for="item in csOptions" :key="item.value" :label="item.label" :value="item.value">
							</el-option>
						</el-select>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row justify="center">
				<el-col :span="11">
					<el-form-item label="维护人：" class="form-item" prop="userName">
						<el-input v-model="params.userName" placeholder="请输入" clearable />
					</el-form-item>
				</el-col>
				<el-col :span="11">
					<el-form-item label="维护时间：">
						<el-col :span="11">
							<el-form-item prop="createStartTime">
								<el-date-picker clearable v-model="params.createStartTime" type="date" placeholder="开始时间"
									value-format="YYYY-MM-DD" :disabled-date="startDisableDate" style="width: 100%" />
							</el-form-item>
						</el-col>
						<el-col :span="1" class="text-center">
							<span class="text-gray-500">-</span>
						</el-col>
						<el-col :span="11">
							<el-form-item prop="createEndTime">
								<el-date-picker clearable v-model="params.createEndTime" type="date" placeholder="结束时间"
									value-format="YYYY-MM-DD" :disabled-date="endDisableDate" style="width: 100%" />
							</el-form-item>
						</el-col>
					</el-form-item>
				</el-col>
			</el-row>
			<el-row justify="center">
				<!-- <el-col :span="11">
					<el-form-item label="维护人所属单位：" class="form-item" prop="maintainerUnit">
						<el-input v-model="params.maintainerUnit" placeholder="" clearable />
					</el-form-item>
				</el-col> -->
				<el-col :span="11">
					<el-form-item label="是否在基础库：" class="form-item" prop="basicLibrary" v-show="isAdmin">
						<el-select v-model="params.basicLibrary" placeholder="请选择" class="form-select" clearable>
							<el-option v-for="item in basicLibraryOptions" :key="item.value" :label="item.label"
								:value="item.value"></el-option>
						</el-select>
					</el-form-item>
				</el-col>
				<el-col :span="11"></el-col>
			</el-row>
			<el-row justify="end">
				<el-form-item class="bottom-button">
					<el-button type="primary" @click="onSearch">查询</el-button>
					<el-button type="primary" @click="onRest">重置</el-button>
					<el-button type="primary" @click="onImport">导入</el-button>
				</el-form-item>
			</el-row>
		</el-form>

		<div class="table-wrapper">
			<el-table class="listTable" ref="multipleTableRef" border :data="tableData" style="width: 100%"
				@selection-change="handleSelectionChange" highlight-current-row @row-click="rowClick" :cell-style="{ border: '1px solid #e5ebf7' }"
				:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
				<el-table-column type="index" width="55" label="序号">
					<template #default="scope">
            		  <span v-text="getIndex(scope.$index)"> </span>
            		</template>
				</el-table-column>
				<el-table-column prop="number" header-align="center" align="center" label="编号" width="180">
					<template #default="{ row }">
						<el-button link type="text" size="small" @click.prevent="onClickNumber(row)">{{ row.number
						}}</el-button>
					</template>
				</el-table-column>
				<el-table-column prop="region" header-align="center" align="center" label="区域" width="180" />
				<el-table-column prop="st" header-align="center" align="center" label="结构类型" width="200" />
				<el-table-column prop="years" header-align="center" align="center" label="年代" width="160" />
				<el-table-column prop="fortification" header-align="center" align="center" label="设防情况" />
				<el-table-column prop="use0" header-align="center" align="center" label="用途" />
				<el-table-column prop="cs" header-align="center" align="center" label="层数" />
				<el-table-column prop="userName" header-align="center" align="center" label="维护人" />
				<el-table-column prop="createTime" header-align="center" align="center" label="维护时间" width="180" />
				<el-table-column prop="basicLibrary" header-align="center" align="center" label="是否在基础库" width="120"
					v-if="isAdmin">
					<template #default="{ row }">
						{{ row.basicLibrary && row.basicLibrary.trim() == '1' ? '是' : '否' }}
					</template>
				</el-table-column>
				<el-table-column label="操作" fixed="right" align="center" width="100" v-if="isAdmin">
					<template #default="{ row }">
						<el-button :type="row.basicLibrary && row.basicLibrary.trim() == '1' ? 'danger' : 'success'" text size="small"
							@click="handleRemove(row)">
							{{ row.basicLibrary && row.basicLibrary.trim() == '1' ? '移出管理库' : '移入管理库' }}
						</el-button>
					</template>
				</el-table-column>
			</el-table>
			<div class="paging">
				<el-pagination background v-model:current-page="queryPagination.pageNo" :layout="layout"
					:page-size="queryPagination.pageSize" :total="queryPagination.total" @current-change="handleCurrentChange"
					@size-change="handleSizeChange" />
			</div>
		</div>
		<div v-show="showMatrix">
			<hr />
			<el-row justify="end" class="table-matrix">
				<el-button type="primary" @click="exportMatrixTableData">导出易损性矩阵</el-button>
				<el-button type="primary" @click="onCurveMatrixSwitch(1)">转换曲线</el-button>
			</el-row>
			<h4>地震易损性矩阵</h4>
			<el-table class="listTables" id="tableRef" ref="tableRef" border :data="tableDataMatrix" style="width: 100%"
				:cell-style="{ border: '1px solid #e5ebf7' }"
				:header-cell-style="{ border: '1px solid #e5ebf7', borderLeft: 'none' }">
				<el-table-column prop="damage" label="破坏程度" align="right" width="150"><el-table-column prop="intensity" label="烈度"
						width="150"></el-table-column></el-table-column>
				<el-table-column header-align="center" align="center" label="基本完好" prop="bs">
					<template #default="scope">{{ scope.row.bs }}</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="轻微破坏" prop="sl">
					<template #default="scope">{{ scope.row.sl }}</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="中等破坏" prop="ml">
					<template #default="scope">{{ scope.row.ml }}</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="严重破坏" prop="el">
					<template #default="scope">{{ scope.row.el }}</template>
				</el-table-column>
				<el-table-column header-align="center" align="center" label="倒塌" prop="c">
					<template #default="scope">{{ scope.row.c }}</template>
				</el-table-column>
			</el-table>
		</div>
		<div v-show="showChart">
			<hr />
			<el-row justify="end" class="table-matrix">
				<el-button type="primary" @click="onCurveMatrixSwitch(0)">转换矩阵</el-button>
			</el-row>
			<div ref="lineChartRef" class="line-chart"></div>
		</div>
	</div>
</template>

<script setup>
import { reactive, toRefs, ref } from "vue";
// 引入接口
import { getInfo } from '@/api/login'
import { getUserId } from "@/utils/auth";
import {
	queryVulnerabilityListApi, //查询
	customMoveBasicLibraryApi, //移入/出基础库
	customGenerateMatrixApi, //生成矩阵或曲线
	customExportMatrixApi, //导出易损性矩阵
	curveMatrixTransformationApi, //曲线矩阵相互转换
} from "@/api/buildingVulnerAnalysis/buildingVulnerAnalysis.js";
import { getProvince, getChildArea } from "@/api/system/division";
// 引入echarts
import * as echarts from "echarts";
// 公用方法
import { parseTime, downloadFile } from "@/utils/ruoyi.js";
// 前端导出excel文件
import { export_json_to_excel } from '@/vendor/Export2Excel';
// 状态管理模块
import useUserStore from "@/store/modules/user";
import useDictStore from "@/store/modules/dict";
import { number } from "echarts/lib/export";
// 获取pinia
const userStore = useUserStore();
const dictStore = useDictStore();
// 是否管理员
const isAdmin = computed(() => userStore.isAdmin || false);
// 用户名
const userName = computed(() => userStore.name || "");
// 所属机构名称
const orgName = computed(() => userStore.orgName || "");

// 获取当前实例
const { proxy } = getCurrentInstance();
// 全局路由对象
const router = useRouter();

// 显示矩阵
let showMatrix = ref(false);
// 显示曲线
let showChart = ref(false);
let provinceAre = ref('') //转换曲线传省

const data = reactive({
	// 表单参数
	params: {
		province: "", //省
		city: "", //市
		county: "", //县
		structureType: "", //结构类型
		structureType1: "",
		years: "", //年代
		fortification: "", //设防情况
		use0: "", //用途
		use1: "",
		cs: "", //层数
		basicLibrary: "", //是否在基础库
		// userName: userName.value, //维护人
		// maintainerUnit: orgName.value, //维护人所属单位
		userName: '', //维护人
		maintainerUnit: '', //维护人所属单位
		createStartTime: "", //开始时间
		createEndTime: "", //结束时间
	},
	// 结构类型
	structureTypeOptions: dictStore.structureTypeOptions || [],
	structureType1Options: [],
	// 年代
	yearsOptions: dictStore.yearsOptions || [],
	// 设防情况
	fortificationOptions: dictStore.fortificationOptions || [],
	// 用途
	useOptions: dictStore.useOptions || [],
	useOptions1: [],
	// 层数
	csOptions: dictStore.csOptions || [],
	//是否在基础库
	basicLibraryOptions: dictStore.basicLibraryOptions || [],

	// 表格
	tableData: [],
	tableDataMatrix: [],
	curRow: {},
	//分页
	layout: " prev, pager, next, jumper, sizes, total",
	queryPagination: {
		pageNo: 1,
		pageSize: 10,
		total: 0,
	},
});
// 将一个响应式对象转换为一个普通对象
const {
	params,
	structureTypeOptions,
	structureType1Options,
	yearsOptions,
	fortificationOptions,
	useOptions,
	useOptions1,
	csOptions,
	basicLibraryOptions,
	tableData,
	tableDataMatrix,
	curRow,
	layout,
	queryPagination,
} = toRefs(data);

// 行政区划
const provinceData = ref([]); //省
const cityData = ref([]); //市
const areaData = ref([]); //区、县
// 获取用户
function getUserInfo() {
	getInfo(getUserId()).then(response => {
		params.value.province=provinceData.value.filter(item=>item.id==response.user.provinceId)[0].name;
		chooseProvince({id:response.user.provinceId,name:params.value.province})
	});
};
/** 获取省列表 */
function getProvinceData() {
	getProvince().then((response) => {
		provinceData.value = response.data;
		getUserInfo()
	});
}
// 选择省份
function chooseProvince(value) {
	params.value.city = null;
	params.value.county = null;
	params.value.province = value.name;
	cityData.value = [];
	areaData.value = [];
	getChildArea(value.id).then((response) => {
		cityData.value = response.data;
	});
}
// 选择城市
function chooseCity(value) {
	params.value.city = value.name;
	params.value.county = null;
	areaData.value = [];
	getChildArea(value.id).then((response) => {
		areaData.value = response.data;
	});
}
// 选择区县
function chooseCounty(value) {
	params.value.county = value.name;
}

// 结构类型选择
const disabledcs = ref(false);
const structureTypeChange = (val) => {
	const structureTypes = structureTypeOptions.value.find(item => item.value === val);
	if (structureTypes) {
		structureType1Options.value = structureTypes.children;
	}
	// 清空选中的二级候选值
	params.value.structureType1 = '';
	// 清空用途
	params.value.use0 = '';
	params.value.use1 = '';
	useOptions1.value = [];
	// 设防情况
	params.value.fortification = '';
	fortificationOptions.value = dictStore.fortificationOptions;
	// 年代
	yearsOptions.value = dictStore.yearsOptions;
	// 过滤楼层预选项
	if (val=='钢筋混凝土结构'||val=='钢结构') {
		csOptions.value = dictStore.csOptions;
		disabledcs.value = false;
		// 用途处理
		useOptions.value = dictStore.useOptions;
	} else if(val=='组合结构'){
		console.log('========');
		// 层数处理
		csOptions.value = dictStore.csOptions.filter((item, index) => index == 2);
		params.value.cs = ''
		disabledcs.value = false;
		// 用途处理
		useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '公寓',
                        label: '公寓'
                    },
                    {
                        value: '学生和职工集体宿舍',
                        label: '学生和职工集体宿舍'
                    },
                    {
                        value: '宾馆',
                        label: '宾馆'
                    },
                    {
                        value: '招待所',
                        label: '招待所'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '办公室',
                        label: '办公室'
                    },
                ]
            },
        ]
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value!='未设防'&&item.value!='自设防'));
	}else if(val=='砌体结构'){
		// 层数处理
		csOptions.value = dictStore.csOptions.filter((item, index) => index < 2);
		disabledcs.value = false;
		// 切换类型时，部分类型楼层没有就"9层以上"选项，则清空
		if (params.value.cs == '9层以上') {
			params.value.cs = ''
		}
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions;
	}else{
		// 层数处理
		disabledcs.value = true;
		csOptions.value = [];
		params.value.cs = ''
		// 用途
		if(val=='土木结构'||val=='木结构'||val=='其他'){
			useOptions.value = [
            {
                value: '第Ⅰ类',
                label: '第Ⅰ类',
                children: [
                    {
                        value: '住宅',
                        label: '住宅'
                    },
                    {
                        value: '其他人员居住场所',
                        label: '其他人员居住场所'
                    }
                ]
            },
            {
                value: '第Ⅲ类',
                label: '第Ⅲ类',
                children: [
                    {
                        value: '除I、II类以外',
                        label: '除I、II类以外'
                    }
                ]
            }
        ]
		if(val=='土木结构'){
		// 设防情况
		fortificationOptions.value = dictStore.fortificationOptions.filter(item=>item.value=='未设防');
		yearsOptions.value = dictStore.yearsOptions.filter((item, index) => index < 4);
		// 切换类型时，年代--选项，则清空
		if (params.value.years == '2010-2016年'||params.value.years == '2016年以后') {
			params.value.years = ''
		}
		}else if(val=='其他'){
			fortificationOptions.value = dictStore.fortificationOptions.filter(item=>(item.value=='未设防'||item.value=='自设防'||item.value=='6度'));
		}
	}else{
			useOptions.value = [
            {
                value: '第Ⅱ类',
                label: '第Ⅱ类',
                children: [
                    {
                        value: '生产车间',
                        label: '生产车间'
                    },
                ]
            },
        ]
		}
	}
};
// 用途选择
const useChange = (val) => {
	const use = useOptions.value.find((item) => item.value === val);
	if (use) {
		useOptions1.value = use.children;
	}
	// 清空选中的二级候选值
	params.value.use1 = '';
};

// 维护时间可选范围控制
const startDisableDate = (time) => {
	let endDateVal = params.value.createEndTime;
	if (endDateVal) {
		return time.getTime() > new Date(endDateVal).getTime();
	}
};
const endDisableDate = (time) => {
	let beginDateVal = params.value.createStartTime;
	if (beginDateVal) {
		return time.getTime() < new Date(beginDateVal).getTime();
	}
};

const getIndex = (index)=>{
  return (
  (queryPagination.value.pageNo-1)*queryPagination.value.pageSize+index+1
  )
}

// 表格
const multipleTableRef = ref();
// 表格选择行
const handleSelectionChange = (val) => {
	// multipleSelection.value = val;
};
// 表格行点击事件
const rowClick = (row, column, event) => {
  if (multipleTableRef.value) {
    // 设置选中效果
    multipleTableRef.value.toggleRowSelection(row);
  }
  // 点击选中当前行
  curRow.value = row;
};
// 分页，每页显示多少行选择
const handleSizeChange = (val) => {
	// 改变每页显示的条数 
	queryPagination.value.pageSize = val;
	// 注意：在改变每页显示的条数时，要将页码显示到第一页
	queryPagination.value.pageNo = 1;
	// 查询
	onSearch();
};
// 分页，当前页数
const handleCurrentChange = (val) => {
	queryPagination.value.pageNo = val;
	// 查询
	onSearch();
};

// 点击编号，展示导入的易损性矩阵或曲线
function onClickNumber(row) {
	provinceAre.value = row.region.split('-')[0];
	if (row?.cbviId) {
		exchange = false;
		curRow.value = row;
		//生成矩阵或曲线
		customGenerateMatrixApi({
			cbviId: row.cbviId || '',
			province:row.region.split('-')[0],
		}).then(res => {
			const { code, data } = res;
			if (code == 200 && data) {
				const { matrix, curve } = data;
				// 概率地震，显示图表
				if (curve) {
					// 隐藏矩阵
					showMatrix.value = false;
					// 显示曲线
					showChart.value = true;
					// DOM元素渲染后处理
					proxy.$nextTick().then(() => {
						// 渲染曲线
						renderChart(curve);
					})
				}
				// 其它，显示矩阵列表
				else if (matrix) {
					// 隐藏曲线
					showChart.value = false;
					// 显示矩阵
					showMatrix.value = true;
					// 设置矩阵数据
					setMatrixData(matrix);
				}
			} else {
				proxy.$modal.msgWarning('生成矩阵或曲线失败！');
			}
		}).catch(err => {
			console.log(err.message);
		})
	}
}
// 移入/出基础库
function handleRemove(row) {
	// 判断是否在基础库中，在则移除，否则移入
	const operate = row.basicLibrary && row.basicLibrary.trim() == '1' ? '0' : '1';
	customMoveBasicLibraryApi({
		id: row.cbviId,
		// 移入1 移出0
		operate: operate,
		province:row.region.split('-')[0],
		// 其它参数
		...row,
	}).then(res => {
		const { code, data } = res;
		if (code == 200) {
			proxy.$modal.msgSuccess(operate == '1' ? '移入成功！' : '移除成功！');
			row.basicLibrary = operate;
		}
	}).catch(err => {
		console.log(err.message);
	})
}

// 查询
const onSearch = () => {
	proxy.$modal.loading('加载中...');
	const query = {
		...params.value,
		page: queryPagination.value.pageNo,
		rows: queryPagination.value.pageSize
	}
	queryVulnerabilityListApi(query).then((res) => {
		proxy.$modal.closeLoading();
		const { code, data } = res;
		if (code === 200 && data) {
			const { total, rows } = data;
			queryPagination.value.total = total || 0;
			//循环遍历之前加上非空判断
			tableData.value = [];
			if (rows && rows.length >= 0) {
				tableData.value = [...rows];
			}
		}
	}).catch(err => {
		proxy.$modal.closeLoading();
		console.log(err.message);
	});
};
//重置
const onRest = () => {
	// 清空表单
	params.value = {
		province:params.value.province,
		city: "", //市
		county: "", //县
		structureType: "", //结构类型
		structureType1: "",
		years: "", //年代
		fortification: "", //设防情况
		use0: "", //用途
		use1: "",
		cs: "", //层数
		basicLibrary: "", //是否在基础库
		userName: '', //维护人
		maintainerUnit: '', //维护人所属单位
		createStartTime: "", //开始时间
		createEndTime: "", //结束时间
	}
	queryPagination.value.pageNo=1;
	// 查询
	onSearch();
};
//导入
const onImport = () => {
	router.push({ path: '/disasterDataManagement/importData/buildingAreaInfo' });
}

// 渲染曲线
function renderChart(data) {
	let myChart = echarts.init(proxy.$refs['lineChartRef']);
	if (myChart && data.length) {
		// x轴
		let xAxisData = [];
		// 预测值
		let cData = [];
		let edData = [];
		let mdData = [];
		let sdData = [];
		// 遍历赋值
		data.sort((a,b)=>{
			return Number(a.im) - Number(b.im)
		})
		console.log(data,'lallal');
		data.map((item, index) => {
			if (item.breakState == "SD") {
				sdData.push(item.fim);
				xAxisData.push(item.im);
			}
			if (item.breakState == "MD") {
				mdData.push(item.fim);
			}
			if (item.breakState == "ED") {
				edData.push(item.fim);
			}
			if (item.breakState == "CD") {
				cData.push(item.fim);
			}
		});
		const option = {
			toolbox: {
				//echart保存为图片
				show: true,
				feature: {
					mark: {
						show: true
					},
					restore: {
						show: true
					},
					saveAsImage: {
						show: true,
						pixelRatio: 1,
						title: '保存为图片',
						type: 'png',
						lang: ['点击保存']
					}
				}
			},
			legend: {
				data: ['轻微(SD)', '中等(MD)', '严重(ED)', '毁坏(Collapse)', '修正(correction)']
			},
			tooltip: {
				trigger: 'axis'
			},
			xAxis: {
				name: 'PGA:(IM)',
				type: 'category',
				data: xAxisData
			},
			yAxis: {
				name: 'F(IM)',
				type: 'value',
				// axisLabel: {
				// 	formatter: '{value}'
				// }
			},
			// 数据颜色
			// color: ['#739cef', '#739cef', '#739cef', '#739cef', '#ff0000'],
			series: [
				// 预测值
				{
					name: '轻微(SD)',
					data: sdData,
					smooth: true,
					type: 'line'
				},
				{
					name: '中等(MD)',
					data: mdData,
					smooth: true,
					type: 'line'
				},
				{
					name: '严重(ED)',
					data: edData,
					smooth: true,
					type: 'line'
				},
				{
					name: '毁坏(Collapse)',
					data: cData,
					smooth: true,
					type: 'line'
				}
			]
		};
		myChart.clear();
		myChart.setOption(option, true);
	} else {
		proxy.$modal.msgWarning("没有曲线数据，不能生成曲线！");
	}
};
// 设置矩阵数据
function setMatrixData(arr) {
	if (arr && arr.length) {
		// 结果列表
		const arrResult = [];
		// 烈度列表
		const arrIntensity = [];
		// 当前行数据
		let curRow = {};
		// 先按烈度排序再处理
		arr.sort((a, b) => {
			return parseInt(a.intensity) < parseInt(b.intensity) ? -1 : 1;
		}).map(item => {
			if (!arrIntensity.includes(item.intensity)) {
				arrIntensity.push(item.intensity);
				curRow = { intensity: item.intensity };
				arrResult.push(curRow);
			}
			switch (item.damage) {
				case '基本完好':
					curRow.bs = item.rate;
					curRow.damageBs = item.damage;
					break;
				case '轻微破坏':
					curRow.sl = item.rate;
					curRow.damageSl = item.damage;
					break;
				case '中等破坏':
					curRow.ml = item.rate;
					curRow.damageMl = item.damage;
					break;
				case '严重破坏':
					curRow.el = item.rate;
					curRow.damageEl = item.damage;
					break;
				case '倒塌':
					curRow.c = item.rate;
					curRow.damageC = item.damage;
					break;
				default:
					break;
			}
		})
		tableDataMatrix.value = arrResult;
	} else {
		tableDataMatrix.value = [];
	}
}
// 导出矩阵列表数据
function exportMatrixTableData() {
	if (tableDataMatrix.value && tableDataMatrix.value.length) {
		// 设置导出数据格式并导出
		const arrData = [];
		tableDataMatrix.value.map(item => {
			arrData.push([item.intensity, item.bs, item.sl, item.ml, item.el, item.c]);
		});
		export_json_to_excel({
			// 表头
			header: ['烈度', '基本完好', '轻微破坏', '中等破坏', '严重破坏', '倒塌'],
			data: arrData,
			filename: '易损性矩阵数据', //文件名
			autoWidth: true,
			bookType: 'xlsx',
		});

		// // 自定义下载
		// customExportMatrixApi({
		// 	cbviId: curRow.value.cbviId || ''
		// }).then(res => {
		// 	if (res) {
		// 		downloadFile(res, `易损性矩阵数据${curRow.value.number ? '(' + curRow.value.number + ')' : ''}.xlsx`);
		// 	} else {
		// 		proxy.$modal.msgError('导出易损性矩阵数据失败！');
		// 	}
		// }).catch(err => {
		// 	proxy.$modal.msgError(err || '导出易损性矩阵数据失败！');
		// });
	} else {
		proxy.$modal.msgWarning('没有矩阵数据，无法导出！');
	}
}

// 是否转换
let exchange = false;
// 曲线矩阵相互转换
function onCurveMatrixSwitch(isTable) {
	// 转换过的直接还原显示
	if(exchange) {
		// 矩阵转曲线
		if (isTable) {
			// 隐藏矩阵
			showMatrix.value = false;
			// 显示曲线
			showChart.value = true;
		}
		// 曲线转矩阵
		else {
			// 隐藏曲线
			showChart.value = false;
			// 显示矩阵
			showMatrix.value = true;
		}
		return false;
	}
	proxy.$modal.loading('转换中,请耐心等待！');
	// 没有转换过的调用接口转换
	curveMatrixTransformationApi({
		id: curRow.value.cbviId,
		province:provinceAre.value,
	}).then(res => {
		// 关闭加载动画
		proxy.$modal.closeLoading();
		// 设置当前行数据已转换
		exchange = true;
		const { code, data } = res;
		if(code == 200) {
			proxy.$modal.msgSuccess('转换成功！');
			// 矩阵转曲线
			if (isTable) {
				// 隐藏矩阵
				showMatrix.value = false;
				// 显示曲线
				showChart.value = true;
				// DOM元素渲染后处理
				proxy.$nextTick().then(() => {
					// 渲染曲线
					renderChart(data);
				})
			}
			// 曲线转矩阵
			else {
				// 隐藏曲线
				showChart.value = false;
				// 显示矩阵
				showMatrix.value = true;
				// 设置矩阵数据
				setMatrixData(data);
			}
		}
	}).catch(err => {
		// 关闭加载动画
		proxy.$modal.closeLoading();
		console.log(err.message);
	})
}
// 获取省份
getProvinceData();
// 挂载
onMounted(() => {
	setTimeout(()=>{
		// 查询
		onSearch();
	},200)

});
</script>

<style lang="scss" scoped>
.form-inline {
	.el-form-item {
		margin-right: 0;
	}
}

.paging {
	margin: 20px 0;
}

// 矩阵
.table-matrix {
	margin-top: 18px;
}

// 折线图
.line-chart {
	width: 100%;
	height: 400px;
	margin: 20px auto;
}
</style>